package cn.dxc.demo.controller;


import cn.dxc.demo.common.ResultMapUtil;
import cn.dxc.demo.entity.User;
import cn.dxc.demo.service.IUserService;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "登录接口")
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;

    /**
     * 登陆接口 用于判断用户名，密码是否正确， 成功则跳转页面
     * @return
     */
    @ApiOperation("登录校验")
    @PostMapping("/toLogin")
    public Object toLogin(@RequestBody User user){
        System.out.println(user);
        if (user.getUsername() == null || user.getPassword() == null) {
            return ResultMapUtil.getHashMapInfo("用户名或密码为空", "0","失败"); }

        final UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        final Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return ResultMapUtil.getHashMapInfo("用户名不存在", "500","失败");
        } catch (IncorrectCredentialsException e) {
            return ResultMapUtil.getHashMapInfo("密码错误", "501","失败");
        }

        final User userByParam = userService.findUserByParam(user);
        return ResultMapUtil.getHashMapInfo(userByParam, "200","成功");

    }

}
